const koaRouter = require('koa-router');
const koaBetterBody = require('koa-better-body');
const koaConvert = require('koa-convert');

let router = new koaRouter({
    prefix: '/task'
});

let task = {
    todoTitle: 'toDoList',
    datas: [{
            ID: 1,
            title: '学习原生Node',
            done: false
        },
        {
            ID: 2,
            title: '学习Koa框架',
            done: true
        },
        {
            ID: 3,
            title: '学习原生Javascript',
            done: false
        },
        {
            ID: 4,
            title: '学习VueJS框架',
            done: true
        },
        {
            ID: 5,
            title: '学习jQuery库',
            done: true
        }
    ]
};

router.get('/', async (ctx, next) => {
    await ctx.render('index', {
        todoTitle: task.todoTitle,
        task: task.datas
    });
});

router.get('/add', async (ctx, next) => {
    await ctx.render('add', {
        todoTitle: task.todoTitle
    });
});

router.post('/add', koaConvert(koaBetterBody({
    buffer: false,
    multipart: false
})), async (ctx, next) => {
    let { title } = ctx.request.fields;
        
    if (!title) {
        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务添加失败',
            path: '/task/add',
            tips: '返回新增页'
        });

        return false;
    } else {
        task.datas.push({
            ID: ++task._id,
            title,
            done: false
        });

        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务添加成功',
            path: '/task',
            tips: '返回首页'
        });
    }
});

router.get('/update/:id', async (ctx, next) => {
    let { id } = ctx.params;

    if (!id) {
        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务更新失败',
            path: '/task',
            tips: '返回首页'
        });
    } else {
        task.datas.find(item => { 
            if (item.ID == id) {
                item.done = !item.done;     
            }
        });

        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务更新成功',
            path: '/task',
            tips: '返回首页'
        });
    }
});

router.get('/delete/:id', async (ctx, next) => {
    let { id } = ctx.params;

    if (!id) {
         await ctx.render('message', {
             todoTitle: task.todoTitle,
             msg: '任务删除失败',
             path: '/task',
             tips: '返回首页'
         });
    } else {
        task.datas = task.datas.filter(item => item.ID != id);

        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务删除成功',
            path: '/task',
            tips: '返回首页'
        });
    }
});

module.exports = router.routes();